<template>
  <div>
    <crumbs :one-level="'县区管理'"></crumbs>
    <el-button type="primary" @click="dialogAddVisible = true">添加</el-button>

    <!-- addForm -->
    <el-dialog
      title="添加县区"
      :visible.sync="dialogAddVisible"
      width="500px"
      :before-close="cleanFormData"
    >
      <el-form :model="countiesForm" ref="countiesForm" label-width="120px">
        <el-form-item
          prop="countiesName"
          label="县区名称"
          :label-width="formLabelWidth"
          :rules="[
            {
              required: true,
              message: '县区名不能为空',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="countiesForm.countiesName"></el-input>
        </el-form-item>
        <el-form-item label="选择日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="countiesForm.countiesDate"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogAddVisible = false;
            countiesForm = init();
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="toInsert('countiesForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-table
      :data="
        tableData.filter(
          (data) => !search || data.countiesName.includes(search)
        )
      "
      style="width: 100%"
    >
      <el-table-column label="日期" prop="countiesDate"> </el-table-column>
      <el-table-column label="县区名" prop="countiesName"> </el-table-column>
      <el-table-column align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"
            :key="scope.$idnex"
          />
        </template>
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- updateForm -->
    <el-dialog
      title="添加县区"
      :visible.sync="dialogUpdateVisible"
      width="500px"
      :before-close="cleanFormData"
    >
      <el-form :model="countiesForm" ref="countiesForm" label-width="120px">
        <el-form-item
          prop="countiesName"
          label="县区名称"
          :label-width="formLabelWidth"
          :rules="[
            {
              required: true,
              message: '县区名不能为空',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input v-model="countiesForm.countiesName"></el-input>
        </el-form-item>
        <el-form-item label="选择日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="countiesForm.countiesDate"
            type="date"
            placeholder="选择日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="
            dialogUpdateVisible = false;
            countiesForm = init();
          "
          >取 消</el-button
        >
        <el-button type="primary" @click="toUpdateByPrimary('countiesForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.current"
        :page-sizes="[4, 6, 8, 10]"
        :page-size="pageInfo.rowMax"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import counties from "@/api/counties.js";

export default {
  data() {
    return {
      tableData: [],
      search: "",
      dialogAddVisible: false,
      dialogUpdateVisible: false,
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
      },
      formLabelWidth: "120px",
      countiesForm: this.init(),
      searchCondition: this.initPageInfo(),
      pageInfo: this.initPageInfo()
    };
  },
  mounted() {
    this.getSelects(this.search);
  },
  methods: {
    initPageInfo() {
      return {
        current: 1,
        rowMax: 8,
        total: 0,
      }
    },
    init() {
      return {
        countiesId: "",
        countiesName: "",
        countiesDate: "",
      };
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogUpdateVisible = true;
      this.countiesForm = row;
    },
    /**
     * 根据主键修改县区
     */
    toUpdateByPrimary() {
      this.$refs["countiesForm"].validate((valid) => {
        if (valid) {
          console.log("updateForm:", this.countiesForm);
          counties
            .updateByPrimary(this.countiesForm)
            .then((res) => {
              let data = res.data;
              if (data.ok) this.$message.success("修改成功");
              else this.$message.eror("修改失败");
              // 跟新表格
              this.getSelects();
            })
            .catch((err) => {
              console.log(err);
            });
        } else this.$message.error("表单错误");
      });
      // 将表单数据清空
      this.dialogUpdateVisible = false;
      this.countiesForm = this.init();
    },
    handleDelete(index, row) {
      console.log(index, row);
      /**
       * 通过主键删除
       */
      counties
        .deleteByPrimary(row.countiesId)
        .then((data) => {
          data = data.data;
          if (data.ok)
            this.$message.success("删除县区:", row.countiesName, "成功");
          else this.$message.error("删除失败");
        })
        .catch((e) => {
          console.log(e);
        });
      // 重新查询数据
      this.getSelects();
    },
    /**
     * 获取所有县区的信息
     */
    getSelects() {
      counties
        .selects(this.searchCondition)
        .then((data) => {
          data = data.data;
          console.log(data);
          if (data.ok) {
            this.tableData = data.data.data || data.data;
            this.pageInfo = data.data;
            console.log("pageInfo:",this.pageInfo);
          } else this.$message.error("县区查询失败");
          console.log(this.tableData);
        })
        .catch((e) => {
          console.log(e);
        });
    },
    /**
     * 添加县区记录
     */
    toInsert() {
      // 验证参数
      this.$refs["countiesForm"].validate((valid) => {
        if (valid) {
          // 取消对话框
          this.dialogAddVisible = false;
          console.log(this.countiesForm);
          counties
            .insert(this.countiesForm)
            .then((data) => {
              data = data.data;
              if (data.ok) this.$message.success("添加成功");
              else this.$message.error("添加失败");
              // 跟新列表数据
              this.getSelects();
            })
            .catch((e) => {
              console.log(e);
            });
          // 将表单绑定的数据清空
          this.countiesForm = this.init();
        } else this.$message.error("表单不符合规定");
      });
    },
    /**
     * 点击对话框的×按钮的时候清理表单数据
     */
    cleanFormData() {
      if (this.dialogAddVisible) this.dialogAddVisible = false;
      if (this.dialogUpdateVisible) this.dialogUpdateVisible = false;
      this.countiesForm = this.init();
    },
    /**
     * 分页
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchCondition.rowMax = val;
      console.log("updateSearchCondition:",this.searchCondition);
      this.getSelects(this.searchCondition);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchCondition.current = val;
      this.getSelects(this.searchCondition);
    },
  },
};
</script>

<style scoped>
.my-form .el-input {
  width: 220px;
}
.my-el-pagination {
  width: 100%;
  height: 10px;
}
.block {
  width: 30vw;
}
.block >>> .number {
  width: 0 !important;
  float: none !important;
}
</style>